package com.usian.admin.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.admin.feign.ArticleFeign;
import com.usian.admin.feign.WemediaFeign;
import com.usian.admin.mapper.AdChannelMapper;
import com.usian.admin.mapper.AdSensitiveMapper;
import com.usian.admin.service.AdChannelService;
import com.usian.admin.service.WemediaNewsAutoScanService;
import com.usian.common.config.FastDFSClientUtil;
import com.usian.common.utils.GreeTextScan;
import com.usian.common.utils.GreenImageScan;
import com.usian.model.admin.dtos.NewsAuthDto;
import com.usian.model.admin.pojos.AdChannel;
import com.usian.model.article.ApArticle;
import com.usian.model.article.ApArticleConfig;
import com.usian.model.article.ApArticleContent;
import com.usian.model.article.ApAuthor;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmNewsVo;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.common.SensitiveWordUtil;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

@Service
@Log4j2
public class WemediaNewsAutoScanServiceImpl implements WemediaNewsAutoScanService {

    @Autowired
    private WemediaFeign wemediaFeign;
    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private AdChannelMapper adChannelMapper;
    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    private FastDFSClientUtil fastDFSClient;
    @Autowired
    private GreeTextScan greeTextScan;
    @Value("${fileServerUrl}")
    private String fileServerUrl;
    @Autowired
    private AdSensitiveMapper adSensitiveMapper;


    /**
     * 根据文章id 审核文章
     *
     * @param id
     */
    @Override
    @GlobalTransactional //seata 分布式事务 统一管理
    public void autoScanByMediaNewsId(Integer id) {

        //1:判断条件
        if (id == null) {
            log.info("文章id为空");
            return;
        }

        //2:id 查询文章
        WmNews wmNews = wemediaFeign.findById(id);
        if (wmNews == null) {
            log.info("根据文章id查询不到文章详情，id={}", id);
            return;
        }

        //3：判断文章的 status  0 草稿 1 提交（待审核）   2 审核失败 3 人工审核   4 人工审核通过  8 审核通过（待发布） 9 已发布
        if (wmNews.getStatus() == 4) {
            //人工审核 走这里审核通过
            saveAppArticle(wmNews);
            return;
        }
        //3.文章状态为8  发布时间<=当前时间 直接保存数据  21 > 20
        if (wmNews.getStatus() == 8 && wmNews.getPublishTime().getTime() <= System.currentTimeMillis()) {
            //保存数据
            saveAppArticle(wmNews);
            return;
        }

        //4:文章状态为1，待审核
        if (wmNews.getStatus() == 1) {
            //调用阿里云 审核文本、审核图片、敏感词
            //抽取文章内容中的纯文本和图片
            Map<String, Object> contentAndImagesResult = handleTextAndImages(wmNews);
            //审核文本
            boolean textScanBoolean = handleTextScan((String) contentAndImagesResult.get("content"), wmNews);
            if(!textScanBoolean){
                return;
            }
            //审核图片
            boolean imagesScanBoolean = handleImagesScan((List<String>) contentAndImagesResult.get("images"), wmNews);
            if(!imagesScanBoolean){
                return;
            }
            //敏感词  更具项目的页面指定黑名单
            boolean sensitiveScanBoolean = handleSensitive((String) contentAndImagesResult.get("content"), wmNews);
            if(!sensitiveScanBoolean){
                return;
            }
            //为1状态的文章审核通过 status 9
            saveAppArticle(wmNews);

        }

    }

    @Override
    public PageResponseResult findNews(NewsAuthDto dto) {
        PageResponseResult responseResult = wemediaFeign.findList(dto);
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    @Override
    public ResponseResult findOne(Integer id) {
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        WmNewsVo wmNewsVo = wemediaFeign.findWmNewsVo(id);
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    @Override
    public ResponseResult updateStatus(Integer type, NewsAuthDto dto) {

        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        WmNews wmNews = wemediaFeign.findById(dto.getId());
        if(wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //type 0 未通过 1通过
        if(type.equals(0)){
            this.updateWmNews(wmNews,(short)2,dto.getMsg());
        }else if(type.equals(1)){
            this.updateWmNews(wmNews,(short)4,"人工审核通过");
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    //通过敏感词列表新 匹配文章内容
    private boolean handleSensitive(String content,WmNews wmNews){
        boolean flag =true;
        List<String> sensitiveList = adSensitiveMapper.findAllSensitive();
        SensitiveWordUtil.initMap(sensitiveList);

        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if(map.size()>0){
            //map有值为敏感词审核不通过
            updateWmNews(wmNews, (short) 2, "文章中文本有违规");
            flag = false;
        }
        return flag;
    }
    //审核图片
    private boolean handleImagesScan(List<String> imageList,WmNews wmNews){
        boolean flag =true;
        if (imageList == null) {
            return true;
        }
        try {
            List<byte[]> imageList1 = new ArrayList<>();
            for(String image : imageList){
                //http:192.168.58.138/group1/m00/moo/dsdsdsdsds.jpg
                //group1/m00/moo/dsdsdsdsds.jpg
                //下载图片
                String imageName = image.replace(fileServerUrl, "");
                int index = imageName.indexOf("/");
                String groupName = imageName.substring(0, index);
                String imagePath = imageName.substring(index + 1);
                byte[] imageByte = new byte[0];
                imageByte = fastDFSClient.download(groupName, imagePath);
                imageList1.add(imageByte);

                //调用审核
                Map map = greenImageScan.imageScan(imageList1);
                if (!map.get("suggestion").equals("pass")) {
                    //审核失败
                    if (map.get("suggestion").equals("block")) {
                        //修改自媒体文章的状态，并告知审核失败原因
                        updateWmNews(wmNews, (short) 2, "文章中图片有违规");
                        flag = false;
                    }

                    //人工审核
                    if (map.get("suggestion").equals("review")) {
                        //修改自媒体文章的状态，并告知审核失败原因
                        updateWmNews(wmNews, (short) 3, "文章图片有不确定元素");
                        flag = false;
                    }
                }
            }

        }catch (Exception e){
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }

    //审核文本
    private boolean handleTextScan(String content,WmNews wmNews){
        boolean flag =true;
        try {
            //阿里云内容文本检测  返回情况 pass 通过  block 失败  review 不确定，不确定进行人工审核
            Map map = greeTextScan.greeTextScan(content);
            if (!map.get("suggestion").equals("pass")) {
                //审核失败
                if (map.get("suggestion").equals("block")) {
                    //修改自媒体文章的状态，并告知审核失败原因
                    updateWmNews(wmNews, (short) 2, "文章内容中有敏感词汇");
                    flag = false;
                }

                //人工审核
                if (map.get("suggestion").equals("review")) {
                    //修改自媒体文章的状态，并告知审核失败原因
                    updateWmNews(wmNews, (short) 3, "文章内容中有不确定词汇");
                    flag = false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
    //提取文章 wmnews 中的文本和图片
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        //文章的内容
        String content = wmNews.getContent();

        //存储纯文本内容
        StringBuilder sb = new StringBuilder();
        //存储图片
        List<String> images = new ArrayList<>();

        List<Map> contentList = JSONArray.parseArray(content, Map.class);
        for (Map map : contentList) {
            if (map.get("type").equals("text")) {
                sb.append(map.get("value"));
            }

            if (map.get("type").equals("image")) {
                images.add((String) map.get("value"));
            }
        }

        if (wmNews.getImages() != null && wmNews.getType() != 0) {
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("content", sb.toString());
        resultMap.put("images", images);
        return resultMap;
    }

    public void saveAppArticle(WmNews wmNews) {
        //保存文章主表 返回文章对象
        ApArticle apArticle = saveArticle(wmNews);
        //保存app文章配置
        saveArticleConfig(apArticle);
        //保存app文章内容
        saveArticleContent(apArticle, wmNews);
        //修改自媒体文章的状态为9
        updateWmNews(wmNews, (short) 9, "审核通过");
    }

    //根据文章wmnews id 修改审核状态 status
    private void updateWmNews(WmNews wmNews, Short status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wemediaFeign.updateWmNews(wmNews);
    }

    //保存文章内容
    private void saveArticleContent(ApArticle apArticle, WmNews wmNews) {
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(wmNews.getContent());
        articleFeign.saveArticleContent(apArticleContent);
    }

    //保存文章的配置
    private void saveArticleConfig(ApArticle apArticle) {
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDelete(false);
        apArticleConfig.setIsDown(true);
        apArticleConfig.setIsComment(true);
        articleFeign.saveArticleConfig(apArticleConfig);
    }

    //保存文章
    private ApArticle saveArticle(WmNews wmNews) {
        ApArticle apArticle = new ApArticle();
        AdChannel adChannel = adChannelMapper.selectById(wmNews.getChannelId());
        if (adChannel != null) {
            apArticle.setChannelId(wmNews.getChannelId());
            apArticle.setChannelName(adChannel.getName());
        }
        apArticle.setTitle(wmNews.getTitle());
        apArticle.setLayout(wmNews.getType());
        apArticle.setImages(wmNews.getImages());
        apArticle.setCreatedTime(new Date());

        //作者
        Integer wmUserId = wmNews.getUserId();
        WmUser wmUser = wemediaFeign.findWmUserById(wmUserId.longValue());
        if (wmUser != null) {
            ApAuthor apAuthor = articleFeign.selectAuthorByName(wmUser.getName());
            if (apAuthor != null) {
                apArticle.setAuthorId(apAuthor.getId().longValue());
                apArticle.setAuthorName(apAuthor.getName());
            }
        }
        ApArticle apArticle1 = articleFeign.saveArticle(apArticle);
        return apArticle1;
    }
}
